import sys

from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QPixmap, QPen, QPainter, QColor
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QWidget, QVBoxLayout, QHBoxLayout

COLORS = ["#000000", "#141923", "#414168", "#3a7fa7", "#35e3e3", "#8fd970", "#5ebb49", "#458352", "#dcd37b","#fffee5","#ffd035","#cc9245","#a15c3e","#a42f3b", "#f45b7a","#c24998", "#81588d", "#bcb0c2", "#ffffff"]

class QPaletteButton(QPushButton):
    def __init__(self, color):
        super().__init__()
        self.setFixedSize(QSize(24, 24))
        self.color = color
        self.setStyleSheet("background-color: %s;" % color)

class Canvas(QLabel):
    def __init__(self):
        super().__init__()

        self._pixmap = QPixmap(600, 300)
        self._pixmap.fill(Qt.white)
        self.setPixmap(self._pixmap)

        self.last_x, last_y = None, None
        self.pen_color = QColor("#000000")

    def set_pen_color(self, c):
        self.pen_color = QColor(c)

    def mouseMoveEvent(self, e):
        if self.last_x is None:
            self.last_x = e.x()
            self.last_y = e.y()
            return

        painter = QPainter(self._pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen()
        pen.setColor(self.pen_color)
        pen.setWidth(3)
        pen.setStyle(Qt.SolidLine)
        pen.setCapStyle(Qt.RoundCap)
        pen.setJoinStyle(Qt.RoundJoin)
        painter.setPen(pen)
        painter.drawLine(self.last_x, self.last_y, e.x(), e.y())
        painter.end()

        self.setPixmap(self._pixmap)

        self.last_x = e.x()
        self.last_y = e.y()

    def mouseReleaseEvent(self, event):
        self.last_x = None
        self.last_y = None


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.canvas = Canvas()
        w = QWidget()
        l = QVBoxLayout()
        l.addWidget(self.canvas)
        w.setLayout(l)

        palette = QHBoxLayout()
        self.add_palette_buttons(palette)
        l.addLayout(palette)

        self.setCentralWidget(w)

    def add_palette_buttons(self, layout):
        for c in COLORS:
            b = QPaletteButton(c)
            b.pressed.connect(lambda c=c: self.canvas.set_pen_color(c))

            layout.addWidget(b)

app = QApplication(sys.argv)
window = MainWindow()
window.setMouseTracking(True)
window.show()
app.exec()